﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using nelech.Models.DBModel;
using System.IO;
using nelech.Models.CalendarModel;
using Google.GData.Calendar;
using Google.GData.Client;
using Google.GData.Extensions;
using System.Linq;
using System.Net;
using nelech.Controllers.Utils;
using System.Text;
using System.Web.UI.MobileControls;
using nelech.Views.Shared.Code;

namespace nelech.Controllers
{
    public partial class AdminController : Controller
    {
        nelechDBEntities db = new nelechDBEntities();

        CalendarService calendarService = new CalendarService("nelech");

        public AdminController()
        {
            calendarService.setUserCredentials("nelech.il@gmail.com", "naftali_25");
        }

[Authorize(Users="admin,editor")]
        public ActionResult Index()
        {
            return View();
        }

        //GET
[Authorize(Users="admin,editor")]
        public ActionResult CreateTrack()
        {
            return View();
        }


        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult CreateTrack([Bind(Exclude = "number,map")]Track track,
            int _cost, int _difficulty, int _duration, int _regeon,
             int _time, int _circle)
        {
            if (!ModelState.IsValid)
                return View();

            BindTrackToMultiselectionEntities(track);
            BindTrack(track, _cost, _difficulty, _duration, _regeon, _time, _circle);
            db.AddToTrack(track);
            AddTrackImages(track);
            track.publish = 1;
            track.chackted = track.chackted == null ? DateTime.Now : track.chackted;
            db.SaveChanges();
            return RedirectToAction("ListTrack", "Admin");
        }

        [Authorize(Users="admin,editor")]
        public ActionResult EditTrack(int id)
        {
            var track = db.Track.First(p => p.number == id);
            track.Cost1Reference.Load();
            track.Difficulty1Reference.Load();
            track.Duration1Reference.Load();
            track.Regeon1Reference.Load();
            track.Circle1Reference.Load();
            track.Time1Reference.Load();
            track.Subject.Load();
            track.Season.Load();
            track.Traffic.Load();
            track.Image.Load();
            return View("CreateTrack", track);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditTrack([Bind(Exclude = "map")]Track track,
            int _cost, int _difficulty, int _duration, int _regeon,
            int _time, int _circle)
        {
            if (!ModelState.IsValid)
                return View("CreateTrack");

            // Get the attached entity
            var p = db.Track.First(r => r.number == track.number);

            // map in the form is <input type="upload"/> and form["map"].ToString() equals
            // to a .Net class name - thus the old path should be put there unless it's
            // changed by AddTrackImages() below
            track.map = p.map;

            // remove entries from many2many relations (must be removed
            // before renewing them below
            UnbindTrackFromMultiselectionEntities(p);
            db.SaveChanges();

            // apply changes from the detached object to the attached one
            db.ApplyPropertyChanges(p.EntityKey.EntitySetName, track);

            // renew enties to many2one relations
            BindTrack(p, _cost, _difficulty, _duration, _regeon, _time, _circle);

            // add the images
            AddTrackImages(p);

            // renew entries to many2many relations
            BindTrackToMultiselectionEntities(p);
            db.SaveChanges();

            return RedirectToAction("ListTrack", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListTrack()
        {
            return View(db.Track.Where(p => p.publish == 1));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult DeleteTrack(int id)
        {
            db.DeleteObject(db.Track.First(p => p.number == id));
            db.SaveChanges();
            return RedirectToAction("ListTrack", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult DeletePlace(int id)
        {
            db.DeleteObject(db.Place.First(p => p.id == id));
            db.SaveChanges();
            return RedirectToAction("ListPlace", "Admin");
        }

        [Authorize(Users="admin,editor")]
        public ActionResult DeleteSpring(int id)
        {
            db.DeleteObject(db.Maayan.First(p => p.id == id));
            db.SaveChanges();
            return RedirectToAction("ListSpring", "Admin");
        }


        [Authorize(Users="admin,editor")]
        public ActionResult CreatePlace()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult CreatePlace([Bind(Exclude = "id,map")]Place place, int _cost, int _regeon)
        {
            if (!ModelState.IsValid)
                return View();
            BindPlace(place, _cost, _regeon);
            db.AddToPlace(place);
            BindPlaceToMultiselectionEntities(place);
            AddPlaceImages(place);
            place.publish = 1;
            place.chackted = place.chackted == null ? DateTime.Now : place.chackted;
            db.SaveChanges();

            return RedirectToAction("ListPlace", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult EditPlace(int id)
        {
            var place = db.Place.First(p => p.id == id);
            place.Cost1Reference.Load();
            place.Regeon1Reference.Load();
            place.Type.Load();
            place.Image.Load();
            place.Season.Load();
            place.Subject.Load();
              ViewData["ListFeedbacks"] = db.Feedback.Where(p => p.parent_id == id && p.FeedbackType.id == 2);
          
            return View("CreatePlace", place);
        }

        [Authorize(Users = "admin,editor")]
        public ActionResult RemoveFeedBack(int id)
        {
            var feed = db.Feedback.First(p => p.id == id);
            
            db.DeleteObject(feed);
            db.SaveChanges();

            return Redirect(Request.UrlReferrer.ToString());
        }

        [Authorize(Users = "admin,editor")]
        public ActionResult RemoveAllFeedBack(int id)
        {
            var feeds = db.Feedback.Where(p => p.parent_id == id);
                foreach(var feed in feeds)
                    {
                        db.DeleteObject(feed);
                     }
          
            db.SaveChanges();

            return Redirect(Request.UrlReferrer.ToString());
        }

        
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditPlace([Bind(Exclude = "map")]Place place, int _cost, int _regeon)
        {
            if (!ModelState.IsValid)
                return View("CreatePlace");

            // Get the attached entity
            var p = db.Place.First(r => r.id == place.id);

            // map in the form is <input type="upload"/> and form["map"].ToString() equals
            // to a .Net class name - thus the old path should be put there unless it's
            // changed by AddTrackImages() below
            place.map = p.map;

            // remove entries from many2many relations (must be removed
            // before renewing them below
            UnbindPlaceFromMultiselectionEntities(p);
            db.SaveChanges();

            // apply changes from the detached object to the attached one
            db.ApplyPropertyChanges(p.EntityKey.EntitySetName, place);

            // renew enties to many2one relations
            BindPlace(p, _cost, _regeon);

            // add the images
            AddPlaceImages(p);

            // renew entries to many2many relations
            BindPlaceToMultiselectionEntities(p);
            db.SaveChanges();

            return RedirectToAction("ListPlace", "Admin");
        }

        [Authorize(Users="admin,editor")]
        public ActionResult ListPlace()
        {
            return View(db.Place.Where(p => p.publish == 1));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult CreateSpring()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult CreateSpring([Bind(Exclude = "id,map")]Maayan m, int _cost, int _nevia, int _regeon)
        {
            if (!ModelState.IsValid)
                return View();

            BindSpring(m, _cost, _nevia, _regeon);
            BindSpringToMultiselectionEntities(m);
            db.AddToMaayan(m);
            AddSpringImages(m);
            m.publish = 1;
            m.chackted = m.chackted == null ? DateTime.Now : m.chackted;
            db.SaveChanges();

            return RedirectToAction("ListSpring", "Admin");
        }

        [Authorize(Users="admin,editor")]
        public ActionResult EditSpring(int id)
        {
            var spring = db.Maayan.First(p => p.id == id);
            spring.Cost1Reference.Load();
            spring.Nevia1Reference.Load();
            spring.Regeon1Reference.Load();
            spring.Image.Load();
            spring.Subject.Load();
            spring.Season.Load();
            return View("createSpring", spring);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditSpring([Bind(Exclude = "map")]Maayan m, int _cost, int _nevia, int _regeon)
        {
            if (!ModelState.IsValid)
                return View("CreateSpring");

            var p = db.Maayan.First(r => r.id == m.id);
            m.map = p.map;
            UnbindSpringFromMultiselectionEntities(p);
            db.SaveChanges();
            db.ApplyPropertyChanges(p.EntityKey.EntitySetName, m);
            BindSpring(p, _cost, _nevia, _regeon);
            BindSpringToMultiselectionEntities(p);
            AddSpringImages(p);
            db.SaveChanges();

            return RedirectToAction("ListSpring", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListSpring()
        {
            return View(db.Maayan.Where(p => p.publish == 1));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RemoveImage(int id)
        {
            var image = db.Image.First(p => p.id == id);
            try
            {
                System.IO.File.Delete(Server.MapPath(image.path));
            }
            catch (Exception e)
            {
            }
            db.DeleteObject(image);
            db.SaveChanges();

            return Redirect(Request.UrlReferrer.ToString());
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RemoveTrackMap(int id)
        {
            var track = db.Track.First(p => p.number == id);
            try
            {
                System.IO.File.Delete(Server.MapPath(track.map));
            }
            catch (Exception e)
            {
            }
            track.map = string.Empty;
            db.SaveChanges();
            return Redirect(Request.UrlReferrer.ToString());
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RemovePlaceMap(int id)
        {
            var place = db.Place.First(p => p.id == id);
            try
            {
                System.IO.File.Delete(Server.MapPath(place.map));
            }
            catch (Exception e)
            {
            }
            place.map = string.Empty;
            db.SaveChanges();
            return Redirect(Request.UrlReferrer.ToString());
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RemoveSpringMap(int id)
        {
            var spring = db.Maayan.First(p => p.id == id);
            try
            {
                System.IO.File.Delete(Server.MapPath(spring.map));
            }
            catch (Exception e)
            {
            }
            spring.map = string.Empty;
            db.SaveChanges();
            return Redirect(Request.UrlReferrer.ToString());
        }
        [Authorize(Users="admin,editor")]
        public ActionResult CreateMunach()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult CreateMunach([Bind(Exclude = "id")]Munach munach)
        {
            if (!ModelState.IsValid)
                return View();

            db.AddToMunach(munach);
            AddMunachImages(munach);
            munach.publish = 1;
            db.SaveChanges();

            return RedirectToAction("ListMunach", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult EditMunach(int id)
        {

            var munach = db.Munach.First(p => p.id == id);
            munach.Image.Load();
            return View("CreateMunach", munach);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditMunach(Munach munach)
        {
            if (!ModelState.IsValid)
                return View("CreateMunach");

            // Get the attached entity
            var m = db.Munach.First(r => r.id == munach.id);


            // apply changes from the detached object to the attached one
            db.ApplyPropertyChanges(m.EntityKey.EntitySetName, munach);

            AddMunachImages(m);


            db.SaveChanges();

            return RedirectToAction("ListMunach", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult DeleteMunach(int id)
        {

            db.DeleteObject(db.Munach.First(p => p.id == id));
            db.SaveChanges();
            return RedirectToAction("ListMunach", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListMunach()
        {
            return View(db.Munach.Where(p => p.publish == 1));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleTrack(int id)
        {
            var t = db.Track.First(p => p.number == id);
            t.publish = 0;
            db.SaveChanges();
            return RedirectToAction("ListTrack", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecyclePlace(int id)
        {
            var t = db.Place.First(p => p.id == id);
            t.publish = 0;
            db.SaveChanges();
            return RedirectToAction("ListPlace", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleSpring(int id)
        {
            var t = db.Maayan.First(p => p.id == id);
            t.publish = 0;
            db.SaveChanges();
            return RedirectToAction("ListSpring", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleTerm(int id)
        {
            var t = db.Munach.First(p => p.id == id);
            t.publish = 0;
            db.SaveChanges();
            return RedirectToAction("ListMunach", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleBinTrack()
        {
            return View(db.Track.Where(p => p.publish == 0));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleBinPlace()
        {
            return View(db.Place.Where(p => p.publish == 0));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleBinMaayan()
        {
            return View(db.Maayan.Where(p => p.publish == 0));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleBinMunach()
        {
            return View(db.Munach.Where(p => p.publish == 0));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RestoreTrack(int id)
        {
            var t = db.Track.First(p => p.number == id);
            t.publish = 1;
            db.SaveChanges();
            return RedirectToAction("RecycleBinTrack", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RestorePlace(int id)
        {
            var t = db.Place.First(p => p.id == id);
            t.publish = 1;
            db.SaveChanges();
            return RedirectToAction("RecycleBinPlace", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RestoreSpring(int id)
        {
            var t = db.Maayan.First(p => p.id == id);
            t.publish = 1;
            db.SaveChanges();
            return RedirectToAction("RecycleBinMaayan", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RestoreMunach(int id)
        {
            var t = db.Munach.First(p => p.id == id);
            t.publish = 1;
            db.SaveChanges();
            return RedirectToAction("RecycleBinMunach", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListText()
        {
            return View(db.Text);
        }
        [Authorize(Users="admin,editor")]
        public ActionResult EditText(int id)
        {
            return View(db.Text.First(p => p.id == id));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditText(Text text)
        {
            var p = db.Text.First(r => r.id == text.id);

            db.ApplyPropertyChanges(p.EntityKey.EntitySetName, text);
            db.SaveChanges();

            return RedirectToAction("ListText", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ShowText(int id)
        {
            switch (id)
            {
                case 1:
                    return RedirectToAction("Safety", "Home");
                case 2:
                    return View();
                case 3:
                    return RedirectToAction("Index", "Home");
                default:
                    return View();
            }
        }
        [Authorize(Users="admin,editor")]
        public ActionResult CreateEvent()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult CreateEvent([Bind(Exclude = "id")]Event e)
        {
            var entry = new EventEntry();
            var author = new AtomPerson(AtomPersonType.Author);
            author.Name = "מנהל האתר";
            author.Email = "nelech.il@gmail.com";
            entry.Authors.Add(author);

            UpdateEventEntryProperties(entry, e);

            var postUri = new Uri("http://www.google.com/calendar/feeds/nelech.il@gmail.com/private/full");

            // Send the request and receive the response:
            var insertedEntry = calendarService.Insert(postUri, entry);
            return RedirectToAction("ListEvent");
        }

        [Authorize(Users="admin,editor")]
        public ActionResult EditEvent(string id)
        {
            id = id.Split(new char[] { '@' })[0];
            var singleQuery = new FeedQuery();
            singleQuery.Uri = new Uri("http://www.google.com/calendar/feeds/nelech.il@gmail.com/private/full/" + id);
            var newFeed = calendarService.Query(singleQuery);
            var retrievedEntry = newFeed.Entries[0];
            var eventEntry = retrievedEntry as EventEntry;
            var eventTime = eventEntry.Times[0];

            var client = new WebClient();
            var data = (eventEntry.WebContentLink != null && eventEntry.WebContentLink.WebContent != null) ? client.DownloadData(eventEntry.WebContentLink.WebContent.Url) : null;
            var result = (eventEntry.WebContentLink != null && eventEntry.WebContentLink.WebContent != null) ? Encoding.UTF8.GetString(data) : null;
            var @event = new Event()
            {
                id = id,
                Day = eventTime.StartTime.Day,
                Details = eventEntry.Content.Content,
                EndHour = eventTime.EndTime.Hour,
                EndMinute = eventTime.EndTime.Minute,
                MceDoc = result,
                Month = eventTime.StartTime.Month,
                Photo = eventEntry.WebContentLink != null ?
                    (eventEntry.WebContentLink.HRef != null ? eventEntry.WebContentLink.HRef.Content : string.Empty) :
                    string.Empty,
                StartHour = eventTime.StartTime.Hour,
                StartMinute = eventTime.StartTime.Minute,
                Title = eventEntry.Title.Text,
                Year = eventTime.StartTime.Year
            };

            return View("CreateEvent", @event);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditEvent(Event e)
        {
            try
            {
                DeleteEvent(e.id);
            }
            catch (Exception exn)
            { 
            }
            return CreateEvent(e);
        }
        [Authorize(Users="admin,editor")]
        public ActionResult DeleteEvent(string id)
        {
            id = id.Split(new char[] { '@' })[0];
            var singleQuery = new FeedQuery();
            singleQuery.Uri = new Uri("http://www.google.com/calendar/feeds/nelech.il@gmail.com/private/full/" + id);
            var newFeed = calendarService.Query(singleQuery);
            var retrievedEntry = newFeed.Entries[0];
            retrievedEntry.Delete();
            return RedirectToAction("ListEvent");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListEvent()
        {
            var query = new FeedQuery();
            query.Uri = new Uri("http://www.google.com/calendar/feeds/nelech.il@gmail.com/private/full");
            var feed = calendarService.Query(query);
            return View(from e in feed.Entries select e as EventEntry);
        }
        [Authorize(Users="admin,editor")]
        public ActionResult KeepAlive(int id)
        {
            return View();
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListRecommendedPlace()
        {
            var publishedPlaces = db.Place.Where(p => p.publish == 1).ToList();
            var listRecPlace = new List<RecommendedPlaceItem>();
            foreach (var place in publishedPlaces)
            {
                var rec = new RecommendedPlace { id = place.id };
                var recPlace = new RecommendedPlaceItem { place = place };
                if (db.RecommendedPlace.AsEnumerable().Contains(rec, new RecommendedPlaceComparer()))
                {
                    recPlace.recommended = true;
                }
                listRecPlace.Add(recPlace);
            }
            return View(listRecPlace);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListRecommendedPlace(FormCollection form)
        {
            foreach (var key in form.AllKeys.Where(p => p.StartsWith("recommended")).ToList())
            {
                foreach (var i in db.RecommendedPlace)
                {
                    db.DeleteObject(i);
                }
                var rec = form[key];
                var myId = int.Parse(key.Substring(11));
                if (rec.StartsWith("true"))
                {
                    var newPlace = new RecommendedPlace() { id = myId };
                    if (!db.RecommendedPlace.AsEnumerable().Contains(newPlace, new RecommendedPlaceComparer()))
                    {
                        db.AddToRecommendedPlace(newPlace);
                    }
                }
                else
                {
                    var place = db.RecommendedPlace.FirstOrDefault(p => p.id == myId);
                    if (place != null)
                    {
                        try
                        {
                            db.DeleteObject(place);
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
            }

            db.SaveChanges();

            return RedirectToAction("ListPlace", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListRecommendedTrack()
        {
            var publishedTracks = db.Track.Where(p => p.publish == 1).ToList();
            var listRecTrack = new List<RecommendedTrackItem>();
            foreach (var track in publishedTracks)
            {
                var rec = new RecommendedTrack { id = track.number };
                var recTrack = new RecommendedTrackItem { track = track };
                if (db.RecommendedTrack.AsEnumerable().Contains(rec, new RecommendedTrackComparer()))
                {
                    recTrack.recommended = true;
                }
                listRecTrack.Add(recTrack);
            }
            return View(listRecTrack);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListRecommendedTrack(FormCollection form)
        {
            foreach (var i in db.RecommendedTrack)
            {
                db.DeleteObject(i);
            }
            foreach (var key in form.AllKeys.Where(p => p.StartsWith("recommended")).ToList())
            {
                var rec = form[key];
                var myId = int.Parse(key.Substring(11));
                if (rec.StartsWith("true"))
                {
                    var newTrack = new RecommendedTrack() { id = myId };
                    if (!db.RecommendedTrack.AsEnumerable().Contains(newTrack, new RecommendedTrackComparer()))
                    {
                        db.AddToRecommendedTrack(newTrack);
                    }
                }
                else
                {
                    var track = db.RecommendedTrack.FirstOrDefault(p => p.id == myId);
                    if (track != null)
                    {
                        try
                        {
                            db.DeleteObject(track);
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
            }

            db.SaveChanges();
            return RedirectToAction("ListTrack", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListRecommendedSpring()
        {
           
            var publishedSprings = db.Maayan.Where(p => p.publish == 1).ToList();
            var listRecSpring = new List<RecommendedSpringItem>();
            foreach (var spring in publishedSprings)
            {
                var rec = new RecommendedSpring { id = spring.id };
                var recSpring = new RecommendedSpringItem { spring = spring };
                if (db.RecommendedSpring.AsEnumerable().Contains(rec, new RecommendedSpringComparer()))
                {
                    recSpring.recommended = true;
                }
                listRecSpring.Add(recSpring);
            }
            return View(listRecSpring);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListRecommendedSpring(FormCollection form)
        {
            foreach (var i in db.RecommendedSpring)
            {
                db.DeleteObject(i);
            }
            foreach (var key in form.AllKeys.Where(p => p.StartsWith("recommended")).ToList())
            {
                var rec = form[key];
                var myId = int.Parse(key.Substring(11));
                if (rec.StartsWith("true"))
                {
                    var newSpring = new RecommendedSpring() { id = myId };
                    if (!db.RecommendedSpring.AsEnumerable().Contains(newSpring, new RecommendedSpringComparer()))
                    {
                        db.AddToRecommendedSpring(newSpring);
                    }
                }
                else
                {
                    var spring = db.RecommendedSpring.FirstOrDefault(p => p.id == myId);
                    if (spring != null)
                    {
                        try
                        {
                            db.DeleteObject(spring);
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
            }

            db.SaveChanges();
            return RedirectToAction("ListSpring", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListPuzzleTopic()
        {
            return View(db.PuzzleTopic.Where(p => p.publish == 1));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult CreatePuzzleTopic()
        {
            return View();
        }

        //POST
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult CreatePuzzleTopic([Bind(Exclude = "id, image , publish")]PuzzleTopic puzzleTopic)
        {
            if (!ModelState.IsValid)
                return View();

            AddPuzzleImages(puzzleTopic);
            puzzleTopic.publish = 1;
            db.AddToPuzzleTopic(puzzleTopic);
            db.SaveChanges();
            return RedirectToAction("ListPuzzleTopic", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult EditPuzzleTopic(int id)
        {
            var puzzleTopic = db.PuzzleTopic.First(p => p.id == id);
            return View("CreatePuzzleTopic", puzzleTopic);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditPuzzleTopic([Bind(Exclude = "image")]PuzzleTopic m)
        {
            if (!ModelState.IsValid)
                return View("CreatePuzzleTopic");

            var p = db.PuzzleTopic.First(r => r.id == m.id);
            m.image = p.image;

            db.ApplyPropertyChanges(p.EntityKey.EntitySetName, m);

            AddPuzzleImages(p);
            db.SaveChanges();

            return RedirectToAction("ListPuzzleTopic", "Admin");

        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecyclePuzzle(int id)
        {
            var puzzle = db.PuzzleTopic.First(p => p.id == id);
            puzzle.publish = 0;
            db.SaveChanges();
            return RedirectToAction("ListPuzzleTopic", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleBinPuzzle()
        {
            return View(db.PuzzleTopic.Where(p => p.publish == 0));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult DeletePuzzle(int id)
        {
            db.DeleteObject(db.PuzzleTopic.First(p => p.id == id));
            db.SaveChanges();
            return RedirectToAction("RecycleBinPuzzle");

        }
        [Authorize(Users="admin,editor")]
        public ActionResult RestorePuzzle(int id)
        {
            var t = db.PuzzleTopic.First(p => p.id == id);
            t.publish = 1;
            db.SaveChanges();
            return RedirectToAction("RecycleBinPuzzle", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListLink()
        {
            return View(db.Link.Where(p => p.publish == 1));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult CreateLink()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult CreateLink([Bind(Exclude = "id")]nelech.Models.DBModel.Link link)
        {
            if (!ModelState.IsValid)
                return View();

            db.AddToLink(link);
            link.publish = 1;
            db.SaveChanges();
            return RedirectToAction("ListLink", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult EditLink(int id)
        {
            var link = db.Link.First(p => p.id == id);
            return View("CreateLink", link);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditLink(nelech.Models.DBModel.Link link)
        {
            if (!ModelState.IsValid)
                return View("CreateLink");

            // Get the attached entity
            var m = db.Link.First(r => r.id == link.id);


            // apply changes from the detached object to the attached one
            db.ApplyPropertyChanges(m.EntityKey.EntitySetName, link);

            db.SaveChanges();

            return RedirectToAction("ListLink", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleLink(int id)
        {
            var t = db.Link.First(p => p.id == id);
            t.publish = 0;
            db.SaveChanges();
            return RedirectToAction("ListLink", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleBinLink()
        {
            return View(db.Link.Where(p => p.publish == 0));
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RestoreLink(int id)
        {
            var t = db.Link.First(p => p.id == id);
            t.publish = 1;
            db.SaveChanges();
            return RedirectToAction("RecycleBinLink", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult DeleteLink(int id)
        {
            db.DeleteObject(db.Link.First(p => p.id == id));
            db.SaveChanges();
            return RedirectToAction("RecycleBinLink");

        }
        [Authorize(Users="admin,editor")]
        public ActionResult ListZimer()
        {
            return View(db.Zimer.Where(p => p.publish == 1).ToList());
        }
        [Authorize(Users="admin,editor")]
        public ActionResult CreateZimer()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult CreateZimer([Bind(Exclude = "id")]Zimer zimer, int _regeon)
        {
            if (!ModelState.IsValid)
                return View();
            db.AddToZimer(zimer);
            AddZimerImages(zimer);
            BindZimer(zimer, _regeon);
            zimer.publish = 1;
            BindZimerToMultiselectionEntities(zimer);
            zimer.chackted = zimer.chackted == null ? DateTime.Now : zimer.chackted;
            db.SaveChanges();
            return RedirectToAction("ListZimer", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult EditZimer(int id)
        {
            var zimer = db.Zimer.First(p => p.id == id);
            zimer.Regeon1Reference.Load();
            zimer.Size.Load();
            zimer.Image.Load();
            return View("CreateZimer", zimer);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditZimer(Zimer zimer, int _regeon)
        {
            if (!ModelState.IsValid)
                return View("CreateZimer");


            // Get the attached entity
            var p = db.Zimer.First(r => r.id == zimer.id);

            // map in the form is <input type="upload"/> and form["map"].ToString() equals
            // to a .Net class name - thus the old path should be put there unless it's
            // changed by AddTrackImages() below


            // remove entries from many2many relations (must be removed
            // before renewing them below
            UnbindZimerFromMultiselectionEntities(p);
            db.SaveChanges();

            // apply changes from the detached object to the attached one
            db.ApplyPropertyChanges(p.EntityKey.EntitySetName, zimer);

            // renew enties to many2one relations
            BindZimer(p, _regeon);

            // add the images
            AddZimerImages(p);

            // renew entries to many2many relations
            BindZimerToMultiselectionEntities(p);
            db.SaveChanges();
            return RedirectToAction("ListZimer", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleZimer(int id)
        {
            var t = db.Zimer.First(p => p.id == id);
            t.publish = 0;
            db.SaveChanges();
            return RedirectToAction("ListZimer", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RecycleBinZimer()
        {
            return View(db.Zimer.Where(p => p.publish == 0).ToList());
        }
        [Authorize(Users="admin,editor")]
        public ActionResult RestoreZimer(int id)
        {
            var t = db.Zimer.First(p => p.id == id);
            t.publish = 1;
            db.SaveChanges();
            return RedirectToAction("RecycleBinZimer", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult DeleteZimer(int id)
        {
            db.DeleteObject(db.Zimer.First(p => p.id == id));
            db.SaveChanges();
            return RedirectToAction("RecycleBinZimer");

        }
        [Authorize(Users="admin,editor")]
        public ActionResult ChoosePuzzle()
        {
            if (db.ChoosenTopic.Count() < 1)
            {
                var puzzle = db.PuzzleTopic.First();
                var choose = new ChoosenTopic() { id = puzzle.id };

                db.AddToChoosenTopic(choose);
                db.SaveChanges();
            }
            return View(db.ChoosenTopic.First());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ChoosePuzzle(ChoosenTopic c)
        {
            if (db.ChoosenTopic.Count() > 0)
            {
                db.DeleteObject(db.ChoosenTopic.First());
                db.SaveChanges();
            }
            db.AddToChoosenTopic(c);

            db.SaveChanges();
            return RedirectToAction("ListPuzzleTopic");
        }
    [Authorize(Users="admin,editor")]
        public ActionResult ListMarquee()
        {
            return View(db.Marquee.ToList());
        }
        [Authorize(Users="admin,editor")]
        public ActionResult CreateMarquee()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult CreateMarquee([Bind(Exclude="id")]Marquee m)
        {
            if (!ModelState.IsValid)
                return View();
            db.AddToMarquee(m);
            db.SaveChanges();
            return RedirectToAction("ListMarquee", "Admin");
        }
       [Authorize(Users="admin,editor")]
        public ActionResult EditMarquee(int id)
        {
            return View("CreateMarquee",db.Marquee.First(p => p.id == id));
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult EditMarquee(Marquee marquee)
        {
            if (!ModelState.IsValid)
                return View("CreateMarquee");
            var m = db.Marquee.First(r => r.id == marquee.id);


            // apply changes from the detached object to the attached one
            db.ApplyPropertyChanges(m.EntityKey.EntitySetName, marquee);

         
            db.SaveChanges();

            return RedirectToAction("ListMarquee", "Admin");
        }
        [Authorize(Users="admin,editor")]
        public ActionResult DeleteMarquee(int id)
        {
            db.DeleteObject(db.Marquee.First(p => p.id == id));
            db.SaveChanges();
            return RedirectToAction("ListMarquee", "Admin");
        }
    }
}

